package com.kaishengit.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kaishengit.dao.UserDao;
import com.kaishengit.entity.User;
import com.kaishengit.util.StringUtil;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String code=request.getParameter("code");
		if(StringUtil.isNotEmpty(code)){
			request.setAttribute("code", code);
		}
		request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		if(StringUtil.isEmpty(username)||StringUtil.isEmpty(password)){
			response.sendRedirect("login.jspx?code=10001");
		}else{
			User user=new UserDao().findUserByName(username);
			if(user!=null){
				if(user.getPassword().equals(password)){
					HttpSession session=request.getSession();
					session.setAttribute("user", user);
					String where=(String)session.getAttribute("where");
					if(where==null||"".equals(where)){
						response.sendRedirect("prod.jspx");
					}else{
						session.removeAttribute("where");
						response.sendRedirect(where);
					}
					
				}else{
					response.sendRedirect("login.jspx?code=10002");
				}
			}else{
				response.sendRedirect("login.jspx?code=10003");
			}
		}
		
	}

}
